package com.zmx.patients.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.IntelligentChatAdapter;
import com.zmx.patients.adapter.IntelligentTitleAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.IntelligentChat;
import com.zmx.patients.pojo.Option;
import com.zmx.patients.pojo.TheDiagnosis;
import com.zmx.patients.view.util.CommonPopWindow;
import com.zmx.patients.view.util.DYLoadingView;
import com.zmx.patients.view.util.PickerScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IntelligentChatActivity extends BaseActivity implements CommonPopWindow.ViewClickListener {

    @BindView(R.id.send)
    Button send;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.reView)
    RecyclerView reView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.chat_layout)
    RelativeLayout chat_layout;
    @BindView(R.id.dyv_layout)
    RelativeLayout dyv_layout;
    @BindView(R.id.choose_layout)
    RelativeLayout choose_layout;
    @BindView(R.id.multiple_choice)
    Button multipleChoice;
    @BindView(R.id.open_button)
    Button open_button;
    @BindView(R.id.dyv)
    DYLoadingView dyv;

    private int num = 1;

    private IntelligentChatAdapter adapter;
    private List<IntelligentChat> lists;

    private List<Option> os;
    private IntelligentTitleAdapter titleAdapter;

    private String str, e_str;

    private List<String> datasBeanList;

    private StringBuffer stringBuffer = new StringBuffer();


    @Override
    protected int getLayoutId() {
        return R.layout.activity_intelligent_chat;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        chat_layout.setVisibility(View.VISIBLE);
        choose_layout.setVisibility(View.GONE);
        dyv_layout.setVisibility(View.GONE);

        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new IntelligentChatAdapter(mActivity,handler);
        reView.setAdapter(adapter);
        lists = new ArrayList<>();

        os = new ArrayList<>();
        //设置LayoutManager
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        //主轴为水平方向，起点在左端
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //定义项目在副轴轴上如何对齐
        flexboxLayoutManager.setAlignItems(AlignItems.CENTER);
        //多个轴对齐方式
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        recyclerView.setLayoutManager(flexboxLayoutManager);


        datasBeanList = new ArrayList<>();
        datasBeanList.add("1小时内");
        datasBeanList.add("3小时内");
        datasBeanList.add("6小时内");
        datasBeanList.add("12小时内");
        datasBeanList.add("1天");
        datasBeanList.add("2天");

        handler.sendEmptyMessage(0);


    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:

                    IntelligentChat ilcs1 = new IntelligentChat();
                    ilcs1.setLogo(0);
                    ilcs1.setTitle("你好，我是你身边智能家庭医生!");
                    lists.add(ilcs1);
                    adapter.setListAndNotifyDataSetChanged(lists);

                    IntelligentChat ilcss = new IntelligentChat();
                    ilcss.setLogo(0);
                    ilcss.setTitle("我学习了上万本医学书籍、上万篇医学指南、千万份临床病例和学术论文，掌握了专业的全科医学知识。");
                    lists.add(ilcss);
                    adapter.notifyDataSetChanged();

                    break;

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Gson gson = new Gson();
                        if (object.getInt("code") == 1) {

                            chat_layout.setVisibility(View.GONE);
                            dyv_layout.setVisibility(View.GONE);
                            choose_layout.setVisibility(View.VISIBLE);

                            num = num + 1;
                            JSONObject data = object.getJSONObject("data");

                            IntelligentChat ic = new IntelligentChat();
                            ic.setId(data.getInt("id"));
                            ic.setLogo(0);
                            ic.setTitle(data.getString("title"));
                            ic.setNums(data.getInt("nums"));
                            ic.setType(data.getInt("type"));
                            ic.setSymptom_id(data.getInt("symptom_id"));

                            if (!data.isNull("option")) {

                                JSONArray array = data.getJSONArray("option");
                                for (int i = 0; i < array.length(); i++) {

                                    Option o = gson.fromJson(array.getJSONObject(i).toString(), Option.class);
                                    o.setSelected(false);
                                    os.add(o);

                                }

                                ic.setLists(os);
                            }

                            lists.add(ic);

                            titleAdapter = new IntelligentTitleAdapter(mActivity, handler, data.getInt("type"),os);
                            recyclerView.setAdapter(titleAdapter);
                            titleAdapter.setListAndNotifyDataSetChanged(os);

                            if (data.getInt("type") == 2) {

                                multipleChoice.setVisibility(View.VISIBLE);

                            } else if (data.getInt("type") == 3) {

                                choose_layout.setVisibility(View.GONE);
                                setAddressSelectorPopup(reView);

                            }

                        } else if (object.getInt("code") == 200) {


                            JSONArray data = object.getJSONArray("data");
                            List<TheDiagnosis> tds = new ArrayList<>();
                            for (int i=0;i<data.length();i++){

                                TheDiagnosis td = gson.fromJson(data.getJSONObject(i).toString(),TheDiagnosis.class);
                                tds.add(td);
                            }

                            IntelligentChat ilcs = new IntelligentChat();
                            ilcs.setLogo(0);
                            StringBuffer sb = new StringBuffer();

                            for (int j=0;j<tds.size();j++){

                                if (j>0||j<tds.size()-1){
                                    sb.append("或");
                                }
                                sb.append("【"+tds.get(j).getDisease()+"】");


                            }
                            ilcs.setTitle("您可能患上了"+sb.toString());
                            ilcs.setHint_message("智能诊疗服务已结束");
                            lists.add(ilcs);

                            num = 1;
                            chat_layout.setVisibility(View.VISIBLE);
                            choose_layout.setVisibility(View.GONE);
                            dyv_layout.setVisibility(View.GONE);
                            stringBuffer.delete(0,sb.length());

                        } else {

                            chat_layout.setVisibility(View.VISIBLE);
                            choose_layout.setVisibility(View.GONE);
                            dyv_layout.setVisibility(View.GONE);
                            IntelligentChat ilcs = new IntelligentChat();
                            ilcs.setLogo(0);
//                            ilcs.setHint_message("智能诊疗服务已结束");
                            ilcs.setTitle(object.getString("msg"));
                            lists.add(ilcs);

                        }

                        dyv.stop();
                        adapter.notifyDataSetChanged();
                        reView.smoothScrollToPosition(lists.size());


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    Option option = (Option) msg.obj;
                    stringBuffer.append("," + option.getValue());
                    str = option.getName();
                    handler.sendEmptyMessage(3);
                    os.clear();
                    titleAdapter.notifyDataSetChanged();
                    break;

                case 3:

                    IntelligentChat ilc = new IntelligentChat();
                    ilc.setLogo(1);
                    ilc.setComtext(str);
                    lists.add(ilc);
                    adapter.notifyDataSetChanged();
                    chat_layout.setVisibility(View.GONE);
                    choose_layout.setVisibility(View.GONE);
                    dyv_layout.setVisibility(View.VISIBLE);
                    dyv.start();

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getInfo();
                        }
                    }, 2000);//2秒后执行Runnable中的run方法


                    break;

            }

        }
    };

    /**
     * 将选择器放在底部弹出框
     *
     * @param v
     */
    private void setAddressSelectorPopup(View v) {
        int screenHeigh = getResources().getDisplayMetrics().heightPixels;
        CommonPopWindow.newBuilder()
                .setView(R.layout.dialog_login)
                .setAnimationStyle(R.style.ActionSheetDialogStyle)
                .setBackgroundDrawable(new BitmapDrawable())
                .setSize(ViewGroup.LayoutParams.MATCH_PARENT, Math.round(screenHeigh * 0.3f))
                .setViewOnClickListener(this)
                .setBackgroundDarkEnable(true)
                .setBackgroundAlpha(0.7f)
                .setBackgroundDrawable(new ColorDrawable(999999))
                .build(this)
                .showAsBottom(v);

    }

    public void getInfo() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("str", e_str);
        params.put("symptom", stringBuffer);
        params.put("num", num);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.common/qt", params, handler, 1, 404);

    }


    @OnClick({R.id.send, R.id.multiple_choice,R.id.open_button})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.send:

                if (TextUtils.isEmpty(message.getText().toString())) {
                    Toast("请输入症状");
                    return;
                }

                str = message.getText().toString();
                e_str = message.getText().toString();
                stringBuffer.append(message.getText().toString());
                handler.sendEmptyMessage(3);
                message.setText("");
                autoInputmethod(mActivity);

                break;

            case R.id.multiple_choice:

                StringBuffer buf = new StringBuffer();

                for (Option o : os) {

                    if (o.isSelected()) {

                        buf.append(o.getName() + " ");

                    }

                }

                str = buf.toString();
                handler.sendEmptyMessage(3);
                os.clear();
                titleAdapter.notifyDataSetChanged();
                multipleChoice.setVisibility(View.GONE);

                break;

            case R.id.open_button:

                AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("退出当前智能诊疗")
                        .setMessage("是否退出当前智能诊疗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                IntelligentChat ilcs = new IntelligentChat();
                                ilcs.setLogo(0);
                                ilcs.setTitle("智能诊疗服务已结束");
                                lists.add(ilcs);
                                adapter.notifyDataSetChanged();
                                reView.smoothScrollToPosition(lists.size());

                                os.clear();
                                num = 1;
                                chat_layout.setVisibility(View.VISIBLE);
                                choose_layout.setVisibility(View.GONE);
                                dyv_layout.setVisibility(View.GONE);
                                stringBuffer.delete(0,stringBuffer.length());

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                return;
                            }
                        }).create();
                alertDialog.show();

                break;


        }


    }

    public static void autoInputmethod(Context context) {

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }


    @Override
    public void getChildView(PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {

            case R.layout.dialog_login:

                TextView imageBtn = view.findViewById(R.id.img_guanbi);
                PickerScrollView addressSelector = view.findViewById(R.id.address);

                // 设置数据，默认选择第一条
                addressSelector.setData(datasBeanList);
                addressSelector.setSelected(0);
                str = datasBeanList.get(0);
                stringBuffer.append("," + datasBeanList.get(0));

                //滚动监听
                addressSelector.setOnSelectListener(new PickerScrollView.onSelectListener() {
                    @Override
                    public void onSelect(String pickers) {

                        str = pickers;
                        stringBuffer.append("," + pickers);
                    }

                });

                //完成按钮
                imageBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();

                        handler.sendEmptyMessage(3);

                    }
                });
                break;
        }
    }
}
